<template>
    <div>
        <!-- <div class="cloginLogo">
             <img src="../../assets/logo2.png"/>
         </div>-->
        <div class="clogin">

            <div class="all" v-if="isAppShow">
                <div id="left-model" class="left-model">

                    <div style="width:187px;margin:auto">
                        <img src="../../assets/logo.png" width="187px" height="137px"
                             style="margin-top:60px;position:absolute" alt=""/>
                    </div>
                    <div style="width:220px;margin:auto;">
                        <span class="fontName" style="margin-top: 210px;position:absolute">安全与环保管理信息平台</span>
                    </div>
                </div>
                <div id="right-model" class="login_box">
                    <!-- <div class="clogin_title" v-show="isAppShow"> -->
                        <!-- <label>用户登录</label> -->
                    <!-- </div> -->

        <Form v-show='loginModel' ref="formInline" :model="formInline" :rules="ruleCustom" style="width: 260px;margin: auto" >
					  <FormItem prop="user" style="margin-bottom: 15px;margin-top: 60px; width: 100%;">
						  <Input placeholder="请输入用户名" v-model="formInline.user" class="clogin_input">
						  <Icon type="ios-person-outline" slot="prepend" style="font-size: 16px"/>
						  <Select v-model="formInline.select" slot="append" @on-change="changeLoginStyle"  class="loginselect">
							  <Option value="bbmg" style="font-size: 10px">bbmg</Option>
							  <Option value="local" style="font-size: 10px">本地</Option>
						  </Select>
						  </Input>
					  </FormItem>
					  <FormItem prop="password" style="margin-bottom: 15px; width: 100%;">
						  <i-input placeholder="请输入密码" v-model="formInline.password" type="password" password
								 class="clogin_input">
						  <Icon type="ios-lock-outline" slot="prepend" style="font-size: 16px;"/>
						  </i-input>
					  </FormItem>
            <FormItem prop="code" style="margin-bottom: 15px; width: 100%;">
              <i-input placeholder="请输入验证码" v-model="formInline.code" style="width: 58%; float: left; height: 38px"
                       class="clogin_input">
                <Icon type="ios-information-circle-outline" slot="prepend" style="font-size: 16px;"/>
              </i-input>
              <div class="login-code">
                <img :src="codeUrl" @click="getCodeImg" class="login-code-img "/>
              </div>
            </FormItem>
					  <FormItem style="margin-bottom: 15px; width: 100%;">
						  <Checkbox v-model="formInline.remeberMe" class="clogin_remeberMe">记住密码</Checkbox>
						   <a @click="loginModel = false" class="clogin_code">忘记密码</a>
					  </FormItem>
					  <FormItem style="margin-bottom: 15px">
						  <Button type="error"  long class="clogin_buttonInput" @onkeydown="loginkeydown"
								  @click="handleSubmit()">登录</Button>
					  </FormItem>
					  <FormItem style="display:flex;justify-content:center">
						  <a @click="QRCode(false)" class="clogin_code">
							  <Icon type="md-tablet-portrait" size="18"/>
							  手机端下载</a>
					  </FormItem>
                    </Form>
					
					<Form v-show='!loginModel' ref="formInline1" :model="formInline1" :rules="ruleCustom1" style="width: 260px;margin: auto">
					  <h3 style="margin-bottom: 15px;margin-top: 20px;margin-left: 100px;">修改密码</h3>
					  <FormItem prop="loginId" style="margin-bottom: 17px;width: 100%;">
					  	 <Input prefix='ios-person-outline' placeholder="请输入用户名" v-model="formInline1.loginId" />
					   </FormItem>
					   <FormItem prop="newPassword" style="margin-bottom: 17px; width: 100%;">
					  	 <Input prefix='ios-lock-outline' placeholder="新密码" v-model="formInline1.newPassword" type="password" password />
					   </FormItem>
					   <FormItem prop="newPassword1" style="margin-bottom: 17px; width: 100%;">
					  	 <Input prefix='ios-lock-outline' placeholder="新密码确认" v-model="formInline1.newPassword1" type="password" password />
					   </FormItem>  
					   <FormItem prop="phoneNumber" style="margin-bottom: 17px; width: 100%;">
					   	 <Input prefix='ios-call' placeholder="填写系统维护的手机号" v-model="formInline1.phoneNumber" />
					   </FormItem>  
					  <FormItem prop="captchaCode" style="margin-bottom: 17px; width: 100%;">
					  	 <Input placeholder="请输入验证码" v-model="formInline1.captchaCode" >
					      <Button type="error" slot="append" @click="getCaptchaCode()">获取验证码</Button>
						 </Input> 
					  </FormItem>
					  <FormItem :label-width="0" style="margin-bottom: 15px">
						  <Button type="error" class="clogin_buttonInput"
						          :loading="buttonLoading"
								  @click="handleSubmit1()">提交</Button>
					  </FormItem>
					</Form>
					
                    <!-- <Form v-else>
                         <FormItem style="margin-top: 20px; color: white; font-size: 18px;">
                             扫描二维码下载手机端
                         </FormItem>
                         <FormItem style="margin-bottom: 10px">
                             <img src="../../assets/img/QRCode.jpg" />
                         </FormItem>
                         <FormItem>
                             <a @click="QRCode(true)" style="color: white"><Icon type="ios-redo-outline" size="18" color="white"/>返回登录页</a>
                         </FormItem>
                     </Form>-->
                </div>
            </div>
            <div class="login_box1" v-else>
                <div style="width:356px;margin:auto;margin-top: 20px;">
                    <span style="color: black;font-size: 18px;margin-left: 16px">
                        请使用<span style="color:red">手机浏览器</span>扫描二维码下载手机端
                    </span>
                </div>
                <div style="margin-left: 10px;margin-top: 5px">
                    <div id="left-model1" style="width: 260px;margin:10px auto;">
                        <img style="width: 240px;height: 260px;" src="../../assets/img/ios.jpg"/>
                    </div>
                    <div id="right-model1" style="width: 260px;margin:10px auto;">
                        <img style="width: 240px;height: 260px;" src="../../assets/img/android.jpg"/>
                    </div>
                </div>
                <div style="width: 216px;margin:10px auto;text-align: center">
                    <a @click="QRCode(true)" class="clogin_code">
                        <Icon type="ios-redo-outline" size="18"/>
                        返回登录页</a>
                </div>
            </div>
        </div>
        <!-- <div class="bottomTips">
             <span style="width:300px">Copyright© 2017-2019 北京中油瑞飞 版权所有</span>
         </div>-->
    </div>
</template>
<script>
import md5 from 'js-md5';
import {Api} from '../../api/index.js'
import {sessionStorage} from '../../common/cacheUtils.js';
import {JSEncrypt} from 'jsencrypt'
// import updatePassword from './updatePassword.vue'

export default {
	    // components:{ updatePassword },
        data() {
            return {
                codeId: "",
                codeUrl: "",
                passwordCheckbox: false,
                styleSwiper: {
                    width: '450px',
                    height: '500px'
                },
                styleSwiperImg: {
                    width: '450px',
                    height: '450px'
                },
                isAppShow: true,
                language: 'zh_CN',
                swiperList: [{
                    id: '1',
                    imgUrl: './assets/img/tooltip1.png'
                }, {
                    id: '2',
                    imgUrl: '../../assets/img/tooltip1.png'
                }, {
                    id: '3',
                    imgUrl: '../../assets/img/tooltip1.png'
                }, {
                    id: '4',
                    imgUrl: '../../assets/img/tooltip1.png'
                }, {
                    id: '5',
                    imgUrl: '../../assets/img/tooltip1.png'
                }],
                languageList: [
                    {
                        value: 'zh_CN',
                        label: '中文'
                    },
                    {
                        value: 'en_US',
                        label: '英文'
                    }
                ],
                ruleCustom: {
                    user: [{
                        validator: (rule, value, callback) => {
                            if (value === '') {
                                callback(new Error(' '));
                            } else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }],
                    password: [{
                        validator: (rule, value, callback) => {
                            if (value === '') {
                                callback(new Error(' '));
                            } else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }],
                    code: [{
                      validator: (rule, value, callback) => {
                        if (value === '') {
                          callback(new Error(' '));
                        } else {
                          callback();
                        }
                      },
                      trigger: 'blur'
                    }],
                },
                formInline: {
                    user: '',
                    password: '',
                    remeberMe:true,
                    select: 'bbmg'
                },
				
				formInline1: {
				    loginId: '',
				    captchaCode: '',
					newPassword:'',
					newPassword1:'',
					phoneNumber:'',
					uuid:''
				},
				ruleCustom1: {
					loginId: [{
					    validator: (rule, value, callback) => {
					        if (value === ''|| value === null || value ===undefined) {
					            callback(new Error('用户名不能为空'));
					        } else {
					            callback();
					        }
					    },
					    trigger: 'blur'
					}],
				    captchaCode: [{
				        validator: (rule, value, callback) => {
				            if (value === '' || value === null || value ===undefined) {
				                callback(new Error('验证码不能为空'));
				            } else {
				                callback();
				            }
				        },
				        trigger: 'blur,change'
				    }],
					newPassword: [{
					  validator: (rule, value, callback) => {
					    if (value == "" || value === null || value ===undefined)
					      callback(new Error('新密码不能为空'));
					    var regex = new RegExp("(?=.*[0-9])(?=.*[a-zA-Z]).{10,16}");
					    if (value.length < 10 || value.length > 16) {
					      callback(new Error("请输入10~16位密码"));
					    } else if (!regex.test(value)) {
					      callback(new Error("必须同时包含字母、数字"));
					    } else {
					      callback();
					    }
					  },
					  required: false,
					  trigger: 'blur'
					}],
					newPassword1: [{
					  validator: (rule, value, callback) => {
					    if (this.formInline1.newPassword !== this.formInline1.newPassword1) {
					      callback('两次密码输入不一致')
					    } else {
					      callback()
					    }
					  },
					  required: false,
					  trigger: 'blur'
					}],
					phoneNumber: [{
					    validator: (rule, value, callback) => {
					        if (!(/^1[23456789]\d{9}$/.test(value))) {
					            callback('请填写有效的的手机号');
					        } else {
					            callback()
					        }
					    },
					    required: true,
					    trigger: 'blur'
					}],
				},
                swiperOption: {
                    spaceBetween: 30,
                    centeredSlides: true,
                    observer: true,
                    observeParents: true,
                    slidesPerView: 1,
                    autoplay: {
                        delay: 2500,
                        disableOnInteraction: false
                    },
                    pagination: {
                        el: '.swiper-pagination',
                        clickable: true
                    }

                },
				loginModel:true,
				buttonLoading:false
            }
        },
        mounted: function () {
             this.$http.get(Api.getVersion).then(res => {
                const version =  res.data.version;  //版本号（每次上线前需要更新下版本号）
                const clientVersion = localStorage.getItem('_version_')
                console.log(version);
                console.log(clientVersion);
                if(clientVersion !== version){
                    localStorage.setItem('_version_', version)
                    console.log("reload window");
//                    window.location.reload();
                    return ;
                }
             })
            this.getCookie();
            let cw = document.body.clientWidth;
            if (cw > 1366) {
                this.styleSwiper.width = '600px';
                this.styleSwiper.height = '650px';
                this.styleSwiperImg.width = '600px';
                this.styleSwiperImg.height = '600px';
            }
        },
        created() {
            let that = this;
            document.onkeydown = function (e) {
                e = window.event || e;
                if (that.$route.path == '/login' && (e.code == 'Enter' || e.code == 'enter')) { //验证在登录界面和按得键是回车键enter
                    that.handleSubmit(); //登录函数
                }
            };
            this.getCodeImg();
        },
        methods: {
          getCodeImg(){
              this.$http.get(Api.validateCode).then(res => {
                if(res.body.result === "true"){
                  this.codeUrl = "data:image/gif;base64," + res.body.img;
                  this.codeId = res.body.uuid;
                }
              })
          },
			getCaptchaCode(){
				let _self = this
				Promise.all(['loginId','phoneNumber','newPassword','newPassword1'].map(item => {
				    return new Promise(function (resolve, reject) {
				        _self.$refs['formInline1'].validateField(item, (error) => {
				            resolve(error)
				        })
				    });
				})).then((data) => {
				    data = data.filter(item => item)
				    if(!data.length){  //通过验证
				        _self.$http.get(Api.getCaptchaCode + _self.formInline1.loginId +'/'+_self.formInline1.phoneNumber).then((res) => {
							if (res.data.result == 'true') {
							   _self.$Message.info(res.data.msg)
						    } else {
							   // _self.$Message.error(res.data.msg);
							   _self.$Message.error({
								   content: res.data.msg,
								   duration: 4
							   });
						    }
				        }).catch(e => {
				            _self.$Message.error("数据获取失败")
				        })
				    } else {  //验证不通过 暂时只提示一个
				        // _self.$Message.error(data[0]);
				    }
				})
			},
            changeLoginStyle(value){
                if(value == "bbmg"){
                     window.location.replace("http://idp.bbmg.com.cn:9012/idp/oauth2/authorize?client_id=bbmgSalfe&redirect_uri=http://http://127.0.0.1:8080/%23/&response_type=code&state=doorSkip");
                }
            },
            QRCode(show) {
                this.isAppShow = show;
            },
            loginkeydown(e) {
                console.log(e)
            },
            getCode(password){
                let encrypt = new JSEncrypt();
                encrypt.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5LY9/MHUWAAWLOKgZcGYZxIglaQj3eNnzgqEMimv4wXe7hTQDC0bzEna3PaXsfk0FR4kKHoGI7Feqc8anAHLpm9Bl2uvD5/db0xk9PzxUJfi1Co3tVf3GMfYJba9DSCPzch/+lkuOazWpnoE43Yz0BYfGrRaPePPxfEW2DttMaQIDAQAB");
                let data = encrypt.encrypt(password);
                return data;
            },
            handleSubmit() {
                this.$refs['formInline'].validate((valid) => {
                    if (valid) {
                        this.$http.get(Api.bbmgLogin, {
							params: {
								loginId: this.formInline.user,
								password: md5(this.formInline.password),
                code: this.formInline.code,
                codeId: this.codeId,
                // captchaEnabled: true,
								type: 'loacl'
							}
						}).then(res => {
							if (res.data.weakPassword && res.data.weakPassword == 'true') {
								// sessionStorage('token').set("passAuthorization", res.data.token);
								this.loginModel = false
								this.$Message.warning(res.data.message);
								this.formInline1={
									// ...this.formInline,
								    loginId: this.formInline.user,
									// password: this.formInline.password,
									newPassword:'',
									newPassword1:''
								}	
								this.$refs['formInline'].resetFields
							} 
							else if (res.data.result == 'true') {
								res.data.data.orgInfo.mainOrgName = res.data.data.orgInfo.orgName;
								res.data.data.mainCompanyName = res.data.data.companyName;
								res.data.data.orgInfo.mainOrgId = res.data.data.orgInfo.orgId;
								res.data.data.mainCompanyCode = res.data.data.companyCode
								res.data.data.mainCompanyId = res.data.data.companyId;
								if (this.formInline.remeberMe) {
									this.setCookie(this.formInline.user, this.formInline.password, 14);
								} else {
									this.clearCookie(this.formInline.user);
								}
								res.data.data.orgInfo.orgId = res.data.data.currentOrgId;
								res.data.data.orgInfo.orgName = res.data.data.currentOrgName;
								res.data.data.companyName = res.data.data.currentCompanyName;
								res.data.data.companyCode = res.data.data.currentCompanyCode;
								res.data.data.companyId = res.data.data.currentCompanyId;
								res.data.data.orgInfo.parentOrgName = res.data.data.currentOrgParentName;
								res.data.data.orgInfo.parentId = res.data.data.currentOrgParentId;
								let data = JSON.stringify(res.data.data);
								sessionStorage('token').set("Authorization", res.data.token);
								sessionStorage('userId').set('userId', data);
								// sessionStorage('userId').set('password', this.formInline.password);
								const userInfo = {
									createUserId: res.data.data.userId,
									createUserName: res.data.data.userName,
									createOrgId: res.data.data.orgInfo.orgId,
									createOrgName: res.data.data.orgInfo.orgName
								}
								sessionStorage('paramUserInfo').set('userInfo', JSON.stringify(userInfo));
					
								// if (res.data.data.updateDate) {
								//     let dateDiff = new Date().getTime() - new Date(res.data.data.updateDate).getTime()//时间差的毫秒数
								//     let dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));
								//     if (dayDiff >= 90) {
								//         this.$Modal.warning({
								//             title: "密码安全提示",
								//             content: '您的密码已有'+ dayDiff +'天未修改！，请立即修改'
								//         });
								//     }
								// }
							  this.$http.get(Api.getRemind+userInfo.createUserId).then(res11 => {
									if (res11.data.data && res11.data.data.length>0) {
										this.$Modal.warning({
											title: "未传企业调查报告提示",
											content: '您上报的事故简报已经审批通过，请及时上传企业调查报告!'
										});
									}
								})
								let redirect = decodeURIComponent('/');
								this.$router.push({path: redirect})
								this.$Message.info('登录成功');
								
							} else {
                this.getCodeImg();
								this.$Message.error(res.data.message);
							}
							// this.buttonLoading = false
						}).catch(e => {
							// this.buttonLoading = false
							console.error(e);
							this.$Message.error('网络异常');
						})
                        
                    }
                });
            },
            handleSubmit1() {
                this.$refs['formInline1'].validate((valid) => {
                    if (valid) {
						this.buttonLoading = true
						let data = {
							password:md5(this.formInline1.newPassword),
							captchaCode:this.formInline1.captchaCode,
							loginId:this.formInline1.loginId,
							phoneNumber:this.formInline1.phoneNumber,
						}
                        this.$http.post(Api.modifyPassword, data).then(res => {
							// sessionStorage('token').del('passAuthorization');
                            if (res.data.result == 'true') {
                                this.formInline ={
                                    user: this.formInline1.loginId,
                                    password: this.formInline1.newPassword,
                                    type: 'loacl',
                                    remeberMe:true,
								}
								this.$refs['formInline1'].resetFields
								this.loginModel = true
								this.buttonLoading = false
								this.$Message.info(res.data.msg);
							}else {
								this.buttonLoading = false
                                this.$Message.error(res.data.msg);
							}
						}).catch(e => {
							this.buttonLoading = false
                            console.error(e);
                            this.$Message.error('网络异常');
                        })
					}
				})
			},
            setCookie(c_name, c_pwd, exdays) {
                var exdate = new Date(); //获取时间
                exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
                //字符串拼接cookie
                window.document.cookie = "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
                window.document.cookie = "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
            },
            //读取cookie
            getCookie: function() {
                if (document.cookie.length > 0) {
                    var arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
                    for (var i = 0; i < arr.length; i++) {
                        var arr2 = arr[i].split('='); //再次切割
                        //判断查找相对应的值
                        if (arr2[0] == 'userName') {
                            this.formInline.user = arr2[1]; //保存到保存数据的地方
                        } else if (arr2[0] == 'userPwd') {
                            this.formInline.password = arr2[1];
                        }
                    }
                }
            },
            //清除cookie
            clearCookie: function(user) {
                this.setCookie(user, "", -1); //修改2值都为空，天数为负1天就好了
            },
            test(){

            }
        }
    }
</script>

<style scoped>
    @media screen and (min-width: 1400px) {
        .clogin {
            background-position: 0px 0px;
        }
    }

    .all {
        width: 680px;
        height: 320px;
        overflow: hidden;
        display: table;
        margin: auto
    }

    #left-model, #right-model {
        display: table-cell;
    }
    #left-model1, #right-model1 {
        display: table-cell;
    }

    .left-model {
        /*flex-direction: column;*/
        /*justify-content: center;*/
        /*align-items: center;*/
        width: 340px;
        height: 320px;
        background: #FFFFFF55;
        position: relative;
        /*margin: auto;*/
    }

    .clogin {
        display: flex;
        justify-content: flex-end;
        background-image: url(../../assets/img/login-bg1.jpg);
        background-repeat: no-repeat;
        background-size: cover;
        width: 100%;
        height: 100vh;
        min-height: 500px;
    }

    .fontName {
        width: 220px;
        height: 23px;
        font-size: 20px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #666465;
    }

    .cloginLogo {
        margin-left: 10vh;
        margin-top: 10vh;
    }

    .login_box {
        /*display: flex;*/
        /*flex-direction: column;*/
        /*justify-content: center;*/
        /*align-items: center;*/
        background: #FFFFFF;
        width: 340px;
        height: 320px;
        /*margin-top:91px;*/
        margin: auto;
        /*border-radius: 10px;*/
    }
    .login_box1 {
        /*display: flex;*/
        /*flex-direction: column;*/
        /*justify-content: center;*/
        /*align-items: center;*/
        background: #FFFFFF;
        width: 510px;
        height: 360px;
        /*margin-top:91px;*/
        margin: auto;
        /*border-radius: 10px;*/
    }
    .clogin_title {
        flex: auto;
        margin-top: 33px;
        width: 73px;
        height: 17px;
        font-size: 18px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #666465;
    }

    .clogin_input {
        width: 260px;
        background: #F9F9F9;
        border: 0 solid #DBDBDB;
        border-radius: 4px;
    }

    .clogin_buttonInput {
        width: 260px;
        height: 34px;
        background: #E3393B;
        border-radius: 4px;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #FFFFFF;
    }

    /* element.style {
         width: 260px;
         margin: auto;
     }*/
    .clogin_remeberMe {
        width: 90px;
        height: 12px;
        font-size: 12px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #B3B3B3;
    }

    .clogin_code {
        width: 100px;
        height: 12px;
        font-size: 12px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #B3B3B3;
    }

    .clogin_code:hover{
        width: 100px;
        height: 12px;
        font-size: 12px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #e3393c;
    }

    .hse_logo {
        margin: 30px;
    }

    .loginselect {
        width: 120px;
        position: relative;
    }

    .bottomTips {
        margin-top: 18px;
        display: flex;
        justify-content: center;
        width: 100%;
        height: 14px;
        font-size: 12px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #757575;
    }

    .bottomTipsA {
        color: #9BADCB;
        padding: 0 15px 0 15px;
        font-family: Microsoft YaHei;
        font-weight: bold;
    }

    .swiper-container {
        width: 100%;
        height: 100%;
        margin-left: 8%;
        margin-top: auto;
        margin-right: auto;
    }

    .swiper1 {
        width: 450px;
        height: 450px;
    }

    .swiper2 {
        width: 600px;
        height: 600px;
    }

    .login-code {
      width: 33%;
      height: 38px;
      float: left;
      padding-left: 10px;
    }
    .login-code img {
      cursor: pointer;
      vertical-align: middle;
    }

    .login-code-img {
      height: 38px;
    }
</style>
